#include <cstdlib>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
private:
    int dfs(TreeNode*& node, int max_val) {
        if (node == nullptr) {
            return 0;
        }
        int self = node->val >= max_val ? 1 : 0;
        max_val = max(node->val, max_val);
        int left = dfs(node->left, max_val);
        int right = dfs(node->right, max_val);
        return left + right + self;
    }
public:
    int goodNodes(TreeNode* root) {
        if (root == nullptr) {
            return 0;
        }
        return dfs(root, INT32_MIN);
    }
};